'''
@author：fc
@date：  2021/11/9
@contact：675435108@qq.com
'''

import json
import matplotlib.pyplot as plt
import numpy as np

"""
文件内容&功能简要：
# 物品本身的流行度也会随时间变化而变化，电影一段时间很热门，但不久就会冷淡,但由于某项事件，电影又会热门起来，如战狼1再战狼2火之后又重燃，
# 我想PoI中的饭店信息也是如此，有活动，位置又会重新火热起来
不过实战的话还是以电影为例，它表现的是自身分数的变化趋势
"""
import os

class Demo:
    def __init__(self, filePath):
        self.dataPath = filePath
        self.users = ['1086360']
        self.items = ['80']

    def showItem(self):
        itemUserRate = dict()
        if os.path.exists("json/itemUserRate.json"):
            itemUserRate = json.load(open("json/itemUserRate.json","r"))
            print("itemUserRate Load Ok ！")
        else:
            for file in os.listdir(self.dataPath):
                onePath = "{}/{}".format(self.dataPath,file)
                print(onePath)
                flag = False
                for line in open(onePath,'r').readlines() : # 按行读
                    if line.strip().endswith(":") and line.strip().split(":")[0] in self.items: # 这里报过一次错，冒号后面有换行，应该要去掉
                        itemId = line.strip().split(":")[0]
                        flag = True
                        continue
                    elif line.strip().endswith(":"):
                        flag = False
                        continue
                    if flag:
                        _, rate, date = line.strip().split(",")
                        itemUserRate.setdefault(itemId, {})
                        newDate = "".join(date.split("-")[:2])
                        itemUserRate[itemId].setdefault(newDate, []).append(int(rate))

            # 计算每个月的平均分
            for itemId in itemUserRate.keys():
                for date in itemUserRate[itemId].keys():
                    itemUserRate[itemId][date] = round(sum(itemUserRate[itemId][date])/len(itemUserRate[itemId][date]),2)
            json.dump(itemUserRate,open("json/itemUserRage.json", "w"))
            print("itemUserRate Message Saved Ok ！")
            return itemUserRate

    def showPicture(self,_dict,label):
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        new_dict = sorted(_dict.items(),key=lambda x:x[0],reverse=False)
        x=[one[0] for one in new_dict]
        y=[one[1] for one in new_dict]
        plt.plot(x,y,marker="o",label=label)
        plt.xticks(np.arange(len(x),step=2),rotation=90)
        plt.xlabel(u"时间-单位/月")
        plt.ylabel(u"平均打分/月")
        plt.title("item评分随时间的变化")
        plt.legend()
        plt.show()


if __name__ == '__main__':
    filePath = "./data/netflix/training_set"
    demo = Demo(filePath)
    itemUserRate =  demo.showItem()
    print(itemUserRate)
    demo.showPicture(itemUserRate[demo.items[0]],"itemId=2")
